#include <avr/io.h>
#include <avr/interrupt.h> 
#include "timer.h"
#include "defines.h"
#include "tx.h"

#define MARK  496
#define SPACE 330


void SetupTimer1(void);
void SetupTimer0(void);

volatile uint8_t pos = 0;
volatile uint8_t byte = 0;
volatile uint8_t parity = 0;

ISR(TIMER0_COMPA_vect)//2 ms
{
	
	TCNT1 = 0;
	BCF(PORTB, 5);
	
	if(pos == 0)
	{
		if(TXfull() == 0)
		{
			OCR1A = MARK;
			return;
		}
		OCR1A = SPACE;
		byte = TXRead();
		parity = 0;
		pos++;
	}
	else if(pos > 0 && pos < 9)
	{
		volatile uint8_t bit = (byte>>(pos-1)) & 1;
		parity += bit;
		if(bit)
			OCR1A = MARK;
		else
			OCR1A = SPACE;

		pos++;
	}
	else if(pos == 9)
	{
		parity %= 2;
		if(parity)
			OCR1A = MARK;
		else
			OCR1A = SPACE;

		pos++;
	}
	else
	{
		OCR1A = MARK;
		pos = 0;
	}
}

void SetupTimers(void)
{
	SetupTimer1();
	SetupTimer0();
	TCNT1 = 0;
	TCNT0 = 0;
	sei();
}

void SetupTimer0(void)
{
	BSF(TCCR0A, WGM01);
	
	OCR0A = 124;//2 ms tick
	
	BSF(TIMSK0, OCIE0A);
	
	//BSF(TCCR0B, CS01);
	//BSF(TCCR0B, CS00);

	BSF(TCCR0B, CS02);//256 prescaler
}

void SetupTimer1(void)
{
	BSF(DDRB, 5);//bit 5 output
	
	BCF(PRR0, PRTIM1);//disable power reduction
	
	BSF(TCCR1B, WGM12);//ctc
	
	BSF(TCCR1A, COM1A0);//toggle on ctc
	
	OCR1A = MARK;
	
	
	BSF(TCCR1B, CS11);//8 prescaler
}
